package com.jl.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload.do")
public class FileUploadController extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/x-www-form-urlencoded");
        req.getHeader("multipart/form-data");
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
            List<FileItem> list = servletFileUpload.parseRequest(req);
            //遍历这个LIST数组(for-in)
            for(FileItem fileItem : list){
                if(fileItem.isFormField()){
                    String fieldName = fileItem.getFieldName();
                    System.out.println(fieldName);
                    String contentType = fileItem.getContentType();
                    System.out.println(contentType);
                }else{
                    //如果不是一个表单文件,就创建一个路径
                    String realPath = getServletContext().getRealPath("/upload");
                    System.out.println(realPath);
                    //UUID是指在一台机器上生成的数字，它保证对在同一时空中的所有机器都是唯一的
                    //在这里就是保证每一个文件都有特有的名字
                    String uuid = UUID.randomUUID().toString();
                    File file = new File(realPath+"/"+uuid+"_"+""+fileItem.getName());
                    if(!file.getParentFile().exists()){
                        file.getParentFile().mkdir();
                    }
                    fileItem.write(file);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
